package com.qf.tenant.manager.service.impl;

import com.qf.common.bean.R;
import com.qf.common.dto.DeviceDto;
import com.qf.common.model.QfDevice;
import com.qf.common.model.QfDeviceTopic;
import com.qf.common.utils.IdWorker;
import com.qf.tenant.manager.feign.DeviceFeign;
import com.qf.tenant.manager.feign.TopicFeign;
import com.qf.tenant.manager.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

/**
 * @author 千锋健哥
 */
@Service
public class DeviceServiceImpl implements DeviceService {

    @Autowired
    private DeviceFeign deviceFeign;

    @Autowired
    private TopicFeign topicFeign;

    @Override
    public R addDevice(DeviceDto dto) {
        //转换dto为pojo实体
        QfDevice device = new QfDevice();
        dto.convertDtoToDo(device);

        //始化deviceKey, device_唯一标识
        IdWorker idWorker = new IdWorker();
        device.setDeviceKey("device_" + idWorker.nextId());

        //设置创建时间
        device.setCreateTime(new Date());
        //设置修改时间
        device.setUpdateTime(new Date());

        //设置是否激活, 默认添加的设备为1未激活
        device.setActive(1);

        //设置设备秘钥, 默认使用随机字符串
        device.setDeviceSecret(UUID.randomUUID().toString().replace("-", ""));
        //设置删除状态
        device.setDeleted(false);

        //设备添加保存
        R<QfDevice> deviceResult = deviceFeign.add(device);

        //级联添加topic设备主题, 上报数据的主题
        QfDeviceTopic deviceTopic1 = new QfDeviceTopic();
        deviceTopic1.setDeviceKey(device.getDeviceKey());
        deviceTopic1.setDeleted(false);
        deviceTopic1.setTopic("/qfjava/device/data/" + device.getDeviceKey());
        deviceTopic1.setCreateTime(new Date());
        deviceTopic1.setUpdateTime(new Date());
        R<QfDeviceTopic> add1 = topicFeign.add(deviceTopic1);

        //级联添加topic设备主题, 平台下发指令topic主题
        QfDeviceTopic deviceTopic2 = new QfDeviceTopic();
        deviceTopic2.setDeviceKey(device.getDeviceKey());
        deviceTopic2.setDeleted(false);
        deviceTopic2.setTopic("/qfjava/device/ctrl/" + device.getDeviceKey());
        deviceTopic2.setCreateTime(new Date());
        deviceTopic2.setUpdateTime(new Date());
        R<QfDeviceTopic> add2 = topicFeign.add(deviceTopic2);

        return deviceResult;
    }

}
